# -*- coding: UTF-8 -*-
'''
Created on 16.06.2014

@author: MathiasAr
'''

import Image, ImageColor
import os


def imageTrim(im, backgrdColors, tolerance=0):
    """imageTrim() --> PIL Image
    im: PIL RGB or RGBA source image
    backgrdColors: tuple with RGB background colors to trim ( (R, G, B), (R, G, B), ... )
    tolerance: color and alpha channel value tolerance +/-
    """
    bands = im.getbands()
    if (not "R" in bands or not "G" in bands or not "B" in bands):
        im = im.convert("RGB")
    pix = im.load()
    minX = im.size[0] - 1
    minY = im.size[1] - 1
    maxX = 0
    maxY = 0

    if backgrdColors and backgrdColors[0].__class__ <> tuple:
        backgrdColors = (backgrdColors,)
        pass 
    
    hasAlpha = False
    if len(pix[0, 0]) > 3:
        hasAlpha = True
    else:
        a = None
    
    for y in range(im.size[1]):
        for x in range(im.size[0]):
            if hasAlpha:
                r, g, b, a = pix[x, y]
            else:
                r, g, b = pix[x, y]
            isBkg = a <> None and a <= tolerance
            if not isBkg and backgrdColors:
                for bkg in backgrdColors:
                    if (r >= bkg[0] - tolerance and r <= bkg[0] + tolerance and g >= bkg[1] - tolerance and g <= bkg[1] + tolerance and b >= bkg[2] - tolerance and b <= bkg[2] + tolerance):
                        isBkg = True
                        break
                    pass
                pass
            if not isBkg:
                if (x < minX):
                    minX = x
                if (y < minY):
                    minY = y
                if (x > maxX):
                    maxX = x
                if (y > maxY):
                    maxY = y
            pass
        pass
    
    if (minX <= maxX) and (minY <= maxY):
        im = im.crop((minX, minY, maxX + 1, maxY + 1))
    return im


trimExt = ".gif"
trimPrefix = "TcBACnetRev12_"

if __name__ == '__main__':
    scanPath = u"C:\\Users\\mathiasar\\Pictures\\TcBACnetRev12"
    trimPath = scanPath + os.path.sep + "trim"
    if (os.path.isdir(scanPath)):
        if not os.path.isdir(trimPath):
            os.makedirs(trimPath)
        for f in os.listdir(scanPath):
            fname = scanPath + os.path.sep + f
            if os.path.isfile(fname):
                ext = os.path.splitext(f)[-1].lower()
                if ext == ".jpg" or ext == ".jpeg" or ext == ".png" or ext == ".gif" or ext == ".bmp":
                    print "Processing: " + fname
                    im = Image.open(fname, "r")
                    im = imageTrim(im, (ImageColor.getrgb("white"), ImageColor.getrgb("red")))
                    im.save(trimPath + os.path.sep + trimPrefix + os.path.splitext(f)[0] + trimExt)
                    pass
    pass
